#include <gfx/DLMap.h>

using namespace gfx;

DLMap::DLMap(	const Map& map, 
			const sf::Image* imgTileSet, 
			const RectTileSet& rectTileSet, 
			const sf::FloatRect& tileDim)
{
	//Initialise la Display List
	m_dLMapId = glGenLists(1);
	
	//Creer la Display List
	glNewList(m_dLMapId, GL_COMPILE);
		if(imgTileSet)
		{
			// Set the texture
			imgTileSet->Bind();

			//itere au travers de toute les cases de la matrices
			for(int x=0;x<map.getWidth();x++)
			{				
				for(int y=0;y<map.getHeight();y++)
				{
					//iterateur pointant vers le rectangle du Tile
					RectTileSet::const_iterator i = rectTileSet.find(map[x][y]);

					//s'assure que le tile de la matrice existe dans le tileset
					if(i!=rectTileSet.end())
					{
						//transforme les coordonner du tileset pour quelle soit des coordonne de texture
						sf::FloatRect tileRect = imgTileSet->GetTexCoords(i->second,1);
						
						//commence a dessiner deux triangle pour faire un carre
						glBegin(GL_TRIANGLES);
						
						//Triangle de gauche
						glTexCoord2f(tileRect.Left,  tileRect.Top);    
						glVertex2f(x*tileDim.GetWidth(), y*tileDim.GetHeight());

						glTexCoord2f(tileRect.Left,  tileRect.Bottom); 
						glVertex2f(x*tileDim.GetWidth(), (y+1)*tileDim.GetHeight());

						glTexCoord2f(tileRect.Right, tileRect.Top); 
						glVertex2f((x+1)*tileDim.GetWidth(), y*tileDim.GetHeight());

						//Triangle de droite
						glTexCoord2f(tileRect.Left,  tileRect.Bottom); 
						glVertex2f(x*tileDim.GetWidth(), (y+1)*tileDim.GetHeight());

						glTexCoord2f(tileRect.Right,  tileRect.Bottom);
						glVertex2f((x+1)*tileDim.GetWidth(),	(y+1)*tileDim.GetHeight());

						glTexCoord2f(tileRect.Right,  tileRect.Top); 
						glVertex2f((x+1)*tileDim.GetWidth(),	y*tileDim.GetHeight());
						glEnd();
					}
					
				}
				
			}
			
		}
	glEndList();


}

DLMap::~DLMap(void)
{
	glDeleteLists(m_dLMapId, 1);
}

void DLMap::Render(sf::RenderTarget& Target) const
{
	int id = m_dLMapId;
	glCallList(id);
}

